<?php

namespace App\Common\Libs;

use App\Consts\GlobalConst;
use Illuminate\Support\Str;

class IdBuilder
{

    /**
     * 生成 24 位随机 ID
     * @param string $time
     * @param string $serverNumber
     * @param int $length
     * @return string
     */
    public static function getUniqueID($time = '', $serverNumber = '00', $length = 24)
    {
        try {
            $time = $time ? $time . random_int(100, 500) : self::getMillisecond();
            $time36 = base_convert($time, 10, 36);
            $randStr = Str::random($length - strlen($serverNumber . $time36));
            $randStr = str_replace(['-', '_'], [random_int(0, 9), random_int(0, 9)], $randStr);
            return strtoupper($serverNumber . $time36 . $randStr);
        } catch (\Exception $e) {
            return Str::random(24);
        }
    }

    /**
     * 获取毫秒级时间戳
     * @return float
     */
    public static function getMillisecond()
    {
        list($microFirst, $microSecond) = explode(' ', microtime());
        return (float)sprintf('%.0f', ((float)$microFirst + (float)$microSecond) * 1000);
    }

    /**
     * @param $value
     * @return array|int
     */
    public static function getSubTable($value)
    {
        if (is_array($value)) {
            return self::getSubTableByArray($value);
        }
        return sprintf('%u', crc32($value)) % GlobalConst::DATABASE_TABLE_NUM;
    }

    /**
     * @param $array
     * @return array
     */
    public static function getSubTableByArray($array)
    {
        $result = [];
        foreach ($array as $value) {
            $tableCount = self::getSubTable($value);
            $result[$tableCount][] = $value;
        }
        return $result;
    }

    /**
     * @param $value
     * @param $baseTableName
     * @return string
     */
    public static function getTableName($value, $baseTableName)
    {
        $tableCount = self::getSubTable($value);
        $tableName = $baseTableName;
        $tableName .= $tableCount;
        return $tableName;
    }

    /**
     * @param $tableCount
     * @param $baseTableName
     * @return string
     */
    public static function getTableNameByTableCount($tableCount, $baseTableName)
    {
        $tableName = $baseTableName;
        $tableName .= $tableCount;
        return $tableName;
    }

}
